require('babel-polyfill');
require('babel-core/register')({
    presets: [
        'es2015',
        'react',
        'stage-0',
    ],
    plugins: ['add-module-exports'],
});
require('css-modules-require-hook')({
    extensions: ['.scss', '.css'],
    preprocessCss: (data, filename) => {
        return require('node-sass').renderSync({
            data,
            file: filename,
        }).css;
    },
});
// Image required hook
require('asset-require-hook')({
    extensions: ['jpg', 'png', 'gif', 'webp'],
    limit: 8000,
});

const Koa = require('koa2');
const bodyParser = require('koa-bodyparser');
const koaLogger = require('koa-logger');
const mount = require('koa-mount');
const staticCache = require('koa-static-cache');
const convert = require('koa-convert');
const json = require('koa-json');
const webpackMiddleware = require('koa-webpack');
const config = require('../webpack.dev.config');
const path = require('path');
const router = require('./routes');
const views = require('koa-views');
const fs = require('fs');
const session = require('koa-session2');
const helmet = require('koa-helmet');
// const jwt = require('jsonwebtoken');
const routerHandle = require('./middlewares/routerHandle');
const checkLogin = require('./middlewares/checkLogin');
const queryHandle = require('./middlewares/queryHandle');

const app = new Koa();

// 一些默认的安全设置
app.use(helmet());
app.use(session({
    key: 'xone',
    maxAge: 2 * 60 * 1000,
    path: '/',
}));
// 预先设置query，用来记录客户端请求的query
app.use(async (ctx, next) => {
    if (!ctx.session.query) {
        ctx.session.query = {};
    }
    await next();
});
// 设置后端视图目录及模板引擎
app.use(views(path.join(__dirname, '../views'), {
    map: {html: 'nunjucks'},
}));
// 日志中间件
app.use(koaLogger());
app.use(bodyParser({
    enableTypes: ['json', 'form', 'text'],
}));
app.use(json());
// 检查是否登录
app.use(checkLogin);
app.use(async (ctx, next) => {
    let manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'public/manifest.json')));
    ctx.session.manifest = manifest;
    await next();
});
app.use(queryHandle);
app.use(router.routes());
app.use(routerHandle);
app.use(router.allowedMethods());
app.use(webpackMiddleware({
    config: config,
    dev: {
        noInfo: false,
        publicPath: config.output.publicPath,
    },
    stats: {
        colors: true,
    },
}));

app.listen(8080);
